<?php
    namespace framework;
    class mysql
    {
        private $host;
        private $port;
        private $user;
        private $password;
        private $database;
        private $link;
        public function __construct($dataAccessName, $database)
        {
            $configuration = parse_ini_file(project::getInstance() -> configurationsPath . 'data_access.ini', true);
            $configuration = $configuration[$dataAccessName];
            $settings = array('host', 'user', 'password');
            foreach($settings as $setting)
            {
                $this -> $setting = $configuration[$setting];
            }
            $this -> port = 3306;
            if(isset($configuration['port']))
            {
                $this -> port = (int) $configuration['port'];
            }
            if(isset($configuration['database']))
            {
                $this -> database = $configuration['database'];
            }
            else
            {
                $this -> database = $database;
            }
            $this -> link = mysql_connect($this ->  host . ':' . $this -> port, $this ->  user, $this ->  password);
            mysql_set_charset('utf8', $this ->  link);
            mysql_select_db($this ->  database, $this ->  link);
        }
        public function escape($string)
        {
            $string = $string[0];
            return mysql_real_escape_string($string, $this -> link);
        }
        public function query($query)
        {
            $query = $query[0];
            if(strtolower(substr($query, 0, 6)) == 'select')
            {
                $data = array();
                $result = mysql_query($query, $this ->  link);
                if(mysql_num_rows($result))
                {
                    while($row = mysql_fetch_assoc($result))
                    {
                        $data[] = $row;
                    }
                }
                mysql_free_result($result);
                return $data;
            }
            else
            {
                mysql_query('START TRANSACTION', $this -> link);
                mysql_query($query, $this ->  link);
                mysql_query('COMMIT', $this -> link);
            }
        }
        public function __destruct()
        {
            mysql_close($this ->  link);
        }
    }